/*
 * Copyright (c) 2009-2010 HIT Microelectronic Center
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *
 * Authors: Gou Pengfei
 *          Jin Yinghan
 *
 * Date: Dec. 2009
 *
 */

#ifndef __CPU_BASE_EDGE_CPU_HH__
#define __CPU_BASE_EDGE_CPU_HH__

#include <iostream>
#include <list>
#include <queue>
#include <set>
#include <vector>

#include "arch/types.hh"
#include "base/statistics.hh"
#include "base/timebuf.hh"
#include "config/full_system.hh"
#include "config/the_isa.hh"
#include "config/use_checker.hh"
#include "cpu/activity.hh"
#include "cpu/base.hh"
#include "cpu/simple_thread.hh"
#include "cpu/edge/comm.hh"
#include "cpu/edge/thread_state.hh"
#include "cpu/edge/insttracer.hh"
#include "sim/process.hh"
#include "params/DerivEdgeCPU.hh"

template <class>
class Checker;
class ThreadContext;
template <class>
class EdgeThreadContext;

class Checkpoint;
class MemObject;
class Process;

class BaseCPUParams;

//class EdgeCPU : public BaseCPU
//{
//  public:
//    EdgeCPU(BaseCPUParams *params);

//    void regStats();

//  protected:
//    Trace::EdgeInstTracer * edge_tracer;

//  public:
//    Trace::EdgeInstTracer * getEdgeTracer() { return edge_tracer; }
//};

typedef uint64_t BlockSeqNum;

class AtomicEdgeCPU;

template<class Impl>
//class BaseEdgeCPU : public EdgeCPU
class BaseEdgeCPU : public BaseCPU
{
  protected:
    Trace::EdgeInstTracer * edge_tracer;

  public:
    Trace::EdgeInstTracer * getEdgeTracer() { return edge_tracer; }

  public:
    // Typedefs from the Impl here.
    typedef typename Impl::CPUPol CPUPolicy;
    typedef typename Impl::EdgeBlockPtr EdgeBlockPtr;
    typedef EdgeThreadState<Impl> ImplState;
    typedef EdgeThreadState<Impl> Thread;
    typedef typename std::list<EdgeBlockPtr>::iterator ListIt;

    friend class EdgeThreadContext<Impl>;

  public:
    /** Five status of CPU */
    enum Status {
        Running,
        Idle,
        Halted,
        Blocked,
        SwitchedOut
    };

    TheISA::TLB * itb;
    TheISA::TLB * dtb;

    /** Overall CPU status. */
    Status _status;

    /** Per-thread status in CPU, used for SMT.  */
    Status _threadStatus[Impl::MaxThreads];

    /**
     * CPU model (AtomicEdgeCPU) for executing instruction block in
     * fetch in order to get the result of a block before it is
     * processed by execute stage. 
     * */
    AtomicEdgeCPU* preExecuteCPU;

  private:
    /** Tick-event of CPU, pushing CPU forward. */
    class TickEvent : public Event
    {
      private:
        /** Pointer to the CPU. */
        BaseEdgeCPU<Impl> *cpu;

      public:
        /** Constructs a tick event. */
        TickEvent(BaseEdgeCPU<Impl> *c);

        /** Processes a tick event, calling tick() on the CPU. */
        void process();
        /** Returns the description of the tick event. */
        const char *description() const;
    };

    /** The tick event used for scheduling CPU ticks. */
    TickEvent tickEvent;

    /** Schedule tick event, regardless of its current state. */
    void scheduleTickEvent(int delay)
    {
        if (tickEvent.squashed())
            reschedule(tickEvent, nextCycle(curTick + ticks(delay)));
        else if (!tickEvent.scheduled())
            schedule(tickEvent, nextCycle(curTick + ticks(delay)));
    }

    /** Unschedule tick event, regardless of its current state. */
    void unscheduleTickEvent()
    {
        if (tickEvent.scheduled())
            tickEvent.squash();
    }

    class ActivateThreadEvent : public Event
    {
      private:
        /** Number of Thread to Activate */
        ThreadID tid;

        /** Pointer to the CPU. */
        BaseEdgeCPU<Impl> *cpu;

      public:
        /** Constructs the event. */
        ActivateThreadEvent();

        /** Initialize Event */
        void init(int thread_num, BaseEdgeCPU<Impl> *thread_cpu);

        /** Processes the event, calling activateThread() on the CPU. */
        void process();

        /** Returns the description of the event. */
        const char *description() const;
    };

    /** Schedule thread to activate , regardless of its current state. */
    void
    scheduleActivateThreadEvent(ThreadID tid, int delay)
    {
        // Schedule thread to activate, regardless of its current state.
        if (activateThreadEvent[tid].squashed())
            reschedule(activateThreadEvent[tid],
                nextCycle(curTick + ticks(delay)));
        else if (!activateThreadEvent[tid].scheduled())
            schedule(activateThreadEvent[tid],
                nextCycle(curTick + ticks(delay)));
    }

    /** Unschedule actiavte thread event, regardless of its current state. */
    void
    unscheduleActivateThreadEvent(ThreadID tid)
    {
        if (activateThreadEvent[tid].scheduled())
            activateThreadEvent[tid].squash();
    }

    /** The tick event used for scheduling CPU ticks. */
    ActivateThreadEvent activateThreadEvent[Impl::MaxThreads];

    class DeallocateContextEvent : public Event
    {
      private:
        /** Number of Thread to deactivate */
        ThreadID tid;

        /** Should the thread be removed from the CPU? */
        bool remove;

        /** Pointer to the CPU. */
        BaseEdgeCPU<Impl> *cpu;

      public:
        /** Constructs the event. */
        DeallocateContextEvent();

        /** Initialize Event */
        void init(int thread_num, BaseEdgeCPU<Impl> *thread_cpu);

        /** Processes the event, calling activateThread() on the CPU. */
        void process();

        /** Sets whether the thread should also be removed from the CPU. */
        void setRemove(bool _remove) { remove = _remove; }

        /** Returns the description of the event. */
        const char *description() const;
    };

    /** Schedule cpu to deallocate thread context.*/
    void
    scheduleDeallocateContextEvent(ThreadID tid, bool remove, int delay)
    {
        // Schedule thread to activate, regardless of its current state.
        if (deallocateContextEvent[tid].squashed())
            reschedule(deallocateContextEvent[tid],
                nextCycle(curTick + ticks(delay)));
        else if (!deallocateContextEvent[tid].scheduled())
            schedule(deallocateContextEvent[tid],
                nextCycle(curTick + ticks(delay)));
    }

    /** Unschedule thread deallocation in CPU */
    void
    unscheduleDeallocateContextEvent(ThreadID tid)
    {
        if (deallocateContextEvent[tid].scheduled())
            deallocateContextEvent[tid].squash();
    }

    /** The tick event used for scheduling CPU ticks. */
    DeallocateContextEvent deallocateContextEvent[Impl::MaxThreads];

  public:
    /** Constructs a CPU with the given parameters. */
    BaseEdgeCPU(DerivEdgeCPUParams *params);
    /** Destructor. */
    ~BaseEdgeCPU();

    /** Registers statistics. */
    void regStats();

    void demapPage(Addr vaddr, uint64_t asn)
    {
        this->itb->demapPage(vaddr, asn);
        this->dtb->demapPage(vaddr, asn);
    }

    void demapInstPage(Addr vaddr, uint64_t asn)
    {
        this->itb->demapPage(vaddr, asn);
    }

    void demapDataPage(Addr vaddr, uint64_t asn)
    {
        this->dtb->demapPage(vaddr, asn);
    }

    /** Returns a specific port. */
    Port *getPort(const std::string &if_name, int idx);

    /** Ticks CPU, calling tick() on each stage, and checking the overall
     *  activity to see if the CPU should deschedule itself.
     */
    void tick();

    /** Initialize the CPU */
    void init();

    /** Returns the Number of Active Threads in the CPU */
    int numActiveThreads()
    { return activeThreads.size(); }

    /** Add Thread to Active Threads List */
    void activateThread(ThreadID tid);

    /** Remove Thread from Active Threads List */
    void deactivateThread(ThreadID tid);

    /** Setup CPU to insert a thread's context */
    void insertThread(ThreadID tid);

    /** Remove all of a thread's context from CPU */
    void removeThread(ThreadID tid);

    /** Count the Total Instructions Committed in the CPU. */
    //virtual Counter totalInstructions() const;
    virtual Counter totalInstructionBlocks() const;

    /** Add Thread to Active Threads List. */
    void activateContext(ThreadID tid, int delay);

    /** Remove Thread from Active Threads List */
    void suspendContext(ThreadID tid);

    /** Remove Thread from Active Threads List &&
     *  Possibly Remove Thread Context from CPU.
     */
    bool deallocateContext(ThreadID tid, bool remove, int delay = 1);

    /** Remove Thread from Active Threads List &&
     *  Remove Thread Context from CPU.
     */
    void haltContext(ThreadID tid);

    /** Activate a Thread When CPU Resources are Available. */
    void activateWhenReady(ThreadID tid);

    /** Add or Remove a Thread Context in the CPU. */
    void doContextSwitch();

    /** Update The Order In Which We Process Threads. */
    void updateThreadPriority();

    /** Serialize state. */
    virtual void serialize(std::ostream &os);

    /** Unserialize from a checkpoint. */
    virtual void unserialize(Checkpoint *cp, const std::string &section);

  public:
#if !FULL_SYSTEM
    /** Executes a syscall.
     * @todo: Determine if this needs to be virtual.
     */
    void syscall(int64_t callnum, ThreadID tid);
#endif

    /** Starts draining the CPU's pipeline of all instructions in
     * order to stop all memory accesses. */
    virtual unsigned int drain(Event *drain_event);

    /** Resumes execution after a drain. */
    virtual void resume();

    /** Signals to this CPU that a stage has completed switching out. */
    void signalDrained();

    /** Switches out this CPU. */
    virtual void switchOut();

    /** Takes over from another CPU. */
    virtual void takeOverFrom(BaseCPU *oldCPU);

    /** Get the current instruction sequence number, and increment it. */
    InstSeqNum getAndIncrementInstSeq()
    { return globalSeqNum++; }

    /** Traps to handle given fault. */
    void trap(Fault fault, ThreadID tid);

    /** Register accessors.  Index refers to the physical register index. */
    /** In Edge, reserve the register methods to allow register operations
    *   between inst blocks.
    */

    /** Reads a miscellaneous register. */
    TheISA::MiscReg readMiscRegNoEffect(int misc_reg, ThreadID tid);

    /** Reads a misc. register, including any side effects the read
     * might have as defined by the architecture.
     */
    TheISA::MiscReg readMiscReg(int misc_reg, ThreadID tid);

    /** Sets a miscellaneous register. */
    void setMiscRegNoEffect(int misc_reg, const TheISA::MiscReg &val,
            ThreadID tid);

    /** Sets a misc. register, including any side effects the write
     * might have as defined by the architecture.
     */
    void setMiscReg(int misc_reg, const TheISA::MiscReg &val,
            ThreadID tid);

    uint64_t readIntReg(int reg_idx);

    TheISA::FloatReg readFloatReg(int reg_idx);

    TheISA::FloatRegBits readFloatRegBits(int reg_idx);

    void setIntReg(int reg_idx, uint64_t val);

    void setFloatReg(int reg_idx, TheISA::FloatReg val);

    void setFloatRegBits(int reg_idx, TheISA::FloatRegBits val);

    uint64_t readArchIntReg(int reg_idx, ThreadID tid);

    float readArchFloatReg(int reg_idx, ThreadID tid);

    uint64_t readArchFloatRegInt(int reg_idx, ThreadID tid);

    /** Architectural register accessors.  Looks up in the commit
     * rename table to obtain the true physical index of the
     * architected register first, then accesses that physical
     * register.
     */
    void setArchIntReg(int reg_idx, uint64_t val, ThreadID tid);

    void setArchFloatReg(int reg_idx, float val, ThreadID tid);

    void setArchFloatRegInt(int reg_idx, uint64_t val, ThreadID tid);

    /** Block PC is the start address of each inst block.
    *   In Edge architecture, fetch stage will maintain a
    *   inst-length PC used to fetch inst from memory while
    *   block PC will be maintained in commit stage indicating
    *   the block commit status.
    *
    */
    Addr getBlockPC(ThreadID tid);

    void setBlockPC(Addr val, ThreadID tid);

    /** Reads the commit PC of a specific thread. */
    Addr readPC(ThreadID tid);

    /** Sets the commit PC of a specific thread. */
    void setPC(Addr new_PC, ThreadID tid);

    /** Reads the next PC of a specific thread. */
    Addr readNextPC(ThreadID tid);

    /** Sets the next PC of a specific thread. */
    void setNextPC(Addr val, ThreadID tid);

    /** Reads the next NPC of a specific thread. */
    Addr readNextNPC(ThreadID tid);

    /** Sets the next NPC of a specific thread. */
    void setNextNPC(Addr val, ThreadID tid);


    /** Initiates a squash of all in-flight instructions for a given
     * thread.  The source of the squash is an external update of
     * state through the TC.
     */
    void squashFromTC(ThreadID tid);

    /** Function to add instruction onto the head of the list of the
     *  instruction blocks.  Used when new instruction blocks are fetched.
     */
    ListIt addInstBlock(EdgeBlockPtr &block);

    /** Function to tell the CPU that an instruction block has completed. */
    void instBlockDone(ThreadID tid,int committed_insts );

    /** Add Instruction block to the CPU Remove List*/
    void addToBlockRemoveList(EdgeBlockPtr &block);

    /** Remove an instruction block from the front end of the list.  There's
     *  no restriction on location of the instruction.
     */
    void removeFrontBlock(EdgeBlockPtr &block);

    /** Remove all instruction blocks that are not currently in the ROB. */
    int removeBlocksNotInROB(ThreadID tid);

    /** Remove all instruction blocks younger than the given sequence number. */
    void removeBlocksUntil(const BlockSeqNum &seq_num, ThreadID tid);

    /** Removes the instruction blocks pointed to by the iterator. */
    inline void squashBlockIt(const ListIt &blockIt, ThreadID tid);

    /** Cleans up all instruction blocks on the remove list. */
    void cleanUpRemovedBlocks();

    /** Get the block ID of head inst block in ROB. */
    TheISA::BlockID readHeadInstBlockID( ThreadID tid);

    /** Debug function to print all blocks on the list. */
    void dumpBlocks();

  public:
#ifndef NDEBUG
    int instcount;
    int blockcount;
#endif

    /** List of all the instruction blocks in flight. */
    std::list<EdgeBlockPtr> blockList;

    /** List of all the instruction blocks that will be removed at the end of this
     *  cycle.
     */
    std::queue<ListIt> blockRemoveList;

#ifdef DEBUG
    /** Debug structure to keep track of the sequence numbers still in
     * flight.
     */
    std::set<BlockSeqNum> snList;
#endif

    /** Records if instructions need to be removed this cycle due to
     *  being retired or squashed.
     */
    bool removeBlocksThisCycle;

  protected:

    /** Fetch stage of Edge CPU. */
    typename CPUPolicy::Fetch fetch;

    /** Map stage of Edge CPU. */
    typename CPUPolicy::Map map;

    /** Execute stage of Edge CPU. */
    typename CPUPolicy::Execute execute;

    /** Commit stage of Edge CPU. */
    typename CPUPolicy::Commit commit;

    /** Global register file of Edge CPU. */
    typename CPUPolicy::GlobalRegFile globalRegFile;

    /** RoB of Edge CPU. */
    typename CPUPolicy::ROB rob;

    /** Active Threads List */
    std::list<ThreadID> activeThreads;

    /** Instruction Set Architecture related stuffs. */
    TheISA::ISA isa[Impl::MaxThreads];

  public:
    /** Enum to give each stage a specific index, so when calling
     *  activateStage() or deactivateStage(), they can specify which stage
     *  is being activated/deactivated.
     */
    enum StageIdx {
        FetchIdx,
        MapIdx,
        ExecuteIdx,
        CommitIdx,
        NumStages };

    /** Typedefs from the Impl to get the structs that each of the
     *  time buffers should use.
     */
    typedef typename CPUPolicy::TimeStruct TimeStruct;

    typedef typename CPUPolicy::Fetch2Map Fetch2Map;

    typedef typename CPUPolicy::Map2Execute Map2Execute;

    typedef typename CPUPolicy::Execute2Commit Execute2Commit;


    /** The main time buffer to do backwards communication. */
    TimeBuffer<TimeStruct> timeBuffer;

    /** The fetch stage's instruction block queue. */
    TimeBuffer<Fetch2Map> fetch2mapQueue;

    /** The map stage's instruction block queue. */
    TimeBuffer<Map2Execute> map2executeQueue;

    /** The commit stage's instruction block queue. */
    TimeBuffer<Execute2Commit> execute2commitQueue;

  private:
    /** The activity recorder; used to tell if the CPU has any
     * activity remaining or if it can go to idle and deschedule
     * itself.
     */
    ActivityRecorder activityRec;

  public:
    /** Records that there was time buffer activity this cycle. */
    void activityThisCycle() { activityRec.activity(); }

    /** Changes a stage's status to active within the activity recorder. */
    void activateStage(const StageIdx idx)
    { activityRec.activateStage(idx); }

    /** Changes a stage's status to inactive within the activity recorder. */
    void deactivateStage(const StageIdx idx)
    { activityRec.deactivateStage(idx); }

    /** Wakes the CPU, rescheduling the CPU if it's not already active. */
    void wakeCPU();

    /** Gets a free thread id. Use if thread ids change across system. */
    ThreadID getFreeTid();

  public:
    /** Returns a pointer to a thread context. */
    ThreadContext *
    tcBase(ThreadID tid)
    {
        return thread[tid]->getTC();
    }

    /** The global sequence number counter. */
    BlockSeqNum globalSeqNum;

    /** Event to call process() on once draining has completed. */
    Event *drainEvent;

    /** Counter of how many stages have completed draining. */
    int drainCount;

    /** Pointers to all of the threads in the CPU. */
    std::vector<Thread *> thread;

    /** Whether or not the CPU should defer its registration. */
    bool deferRegistration;

    /** Is there a context switch pending? */
    bool contextSwitch;

    /** Threads Scheduled to Enter CPU */
    std::list<int> cpuWaitList;

    /** The cycle that the CPU was last running, used for statistics. */
    Tick lastRunningCycle;

    /** The cycle that the CPU was last activated by a new thread*/
    Tick lastActivatedCycle;

    /** Mapping for system thread id to cpu id */
    std::map<ThreadID, unsigned> threadMap;

    /** Available thread ids in the cpu*/
    std::vector<ThreadID> tids;

    /** CPU read function, forwards read to LSQ. */
    template <class T>
    Fault read(RequestPtr &req, T &data, int load_idx)
    {
        this->execute.ldstQueue.read(req, data, load_idx);
        return NoFault;
    }

    /** CPU write function, forwards write to LSQ. */
    template <class T>
    Fault write(RequestPtr &req, T &data, int store_idx)
    {
        this->execute.ldstQueue.write(req, data, store_idx);
        return NoFault;
    }

    Addr lockAddr;

    /** Temporary fix for the lock flag, works in the UP case. */
    bool lockFlag;

    /** How many ExeUnits this cpu has. Default to 1. */
    int numExeUnits;

    /** The topology of distributed exeUnits. */
    int exeUnitsXMax;
    int exeUnitsYMax;

    /** Statistics statements. */

    /** Stat for total number of times the CPU is descheduled. */
    Stats::Scalar timesIdled;
    /** Stat for total number of cycles the CPU spends descheduled. */
    Stats::Scalar idleCycles;
    /** Stat for the number of committed blocks per thread. */
    Stats::Vector committedBlocks;
    /** Stat for the number of committed insts ( the executed insts ) per thread. */
    Stats::Vector committedInsts;
    /** Stat for the total number of committed blocks. */
    Stats::Scalar totalCommittedBlocks;
    /** Stat for the total number of committed insts ( the executed insts ). */
    Stats::Scalar totalCommittedInsts;
    /** Stat for the CPI per thread. */
    Stats::Formula cpi;
    /** Stat for the total CPI. */
    Stats::Formula totalCpi;
    /** Stat for the IPC per thread. */
    Stats::Formula ipc;
    /** Stat for the total IPC. */
    Stats::Formula totalIpc;
};

#endif // __CPU_EDGE_CPU_HH__
